package com.gulimall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.common.constant.AuthServerConstant;
import com.common.utils.HttpUtils;
import com.common.utils.R;
import com.gulimall.auth.feign.MemberFeignService;
import com.common.vo.MemberRespVo;
import com.gulimall.auth.vo.SocialUser;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * 处理社交登录
 */
@Controller
public class OAuth2Controller {

    @Autowired
    MemberFeignService memberFeignService;

    @GetMapping("/oauth2.0/weibo/success")
    public String weibo(@RequestParam("code") String code, RedirectAttributes redirectAttributes, HttpSession httpSession) throws Exception {

        Map<String, String> map = new HashMap<>();
        map.put("client_id","2077705774");
        map.put("client_secret","40af02bd1c7e435ba6a6e9cd3bf799fd");
        map.put("grant_type","authorization_code");
        map.put("redirect_uri","http://auth.gulimall.com/oauth2.0/weibo/success");
        map.put("code",code);
        HttpResponse response = HttpUtils.doPost("https://api.weibo.com", "/oauth2/access_token", "post", new HashMap<>(), map, new HashMap<>());
        if (response.getStatusLine().getStatusCode()==200){
            //获取到accessToken
            String json = EntityUtils.toString(response.getEntity());
            SocialUser socialUser = JSON.parseObject(json, SocialUser.class);
            //1、登录或者注册
            R r = memberFeignService.oauthlogin(socialUser);
            if (r.getCode() == 0){
                MemberRespVo logUser = r.getData("data", new TypeReference<MemberRespVo>() {});
                //session不能跨域名共享
                httpSession.setAttribute(AuthServerConstant.LOGIN_USER,logUser);
                return "redirect:http://gulimall.com";
            }else {
                //失败
                HashMap<String, String> hashMap = new HashMap<>();
                hashMap.put("data",r.getData("msg",new TypeReference<String>(){}));
                redirectAttributes.addFlashAttribute("errors",hashMap);
                return  "redirect:http://auth.gulimall.com/login.html";
            }
        }else {
            return "redirect:http://auth.gulimall.com/login.html";
        }
    }

















}
